/**
 * 添加拦截器：
 *    拦截request请求
 *    拦截uploadFile 文件上传
 * 
 * 
 * TODO:
 * 1.非http开头的需要拼接地址
 * 2.请求超时
 * 3.添加小程序端请求头标识
 * 4.添加token请求头标识
 * 
 */

import { useMemberStore } from "../stores/models/menbers";

var baseURL = 'h5-api/api/v1'
function changeUrl(){
	switch (uni.getSystemInfoSync().platform) {
		case 'android':
			console.log('运行Android上');
			baseURL = 'https://api.stone09.com/api/v1'
			break;
		case 'ios':
			console.log('运行iOS上');
			baseURL = 'https://api.stone09.com/api/v1'
			break;
		case 'mp-weixin':
			console.log('运行mp-weixin上');
			baseURL = 'https://api.stone09.com/api/v1'
			break;
		case 'mp-h5':
				console.log('运行h5上');
				baseURL = 'h5-api/api/v1'
				break;
		default:
			console.log('运行在开发者工具上');
			baseURL = 'https://api.stone09.com/api/v1'
			break;
	}
}

changeUrl();


const httpInterceptor = {
	invoke(options: UniApp.RequestOptions) {
		if (!options.url.startsWith('http')) {
			options.url = baseURL + options.url;
		}
		options.timeout = 10000;
		options.header = {
			...options.header,
			'source-client': 'miniapp',
			'Access-Control-Allow-Origin': '*'
		}
		const memberStore = useMemberStore()
		const token = memberStore.profile?.token
		if (token) {
			options.header.Authorization ="Bearer "+token
		} else {
			options.header.Authorization = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcGVuaWQiOiJ0ZXN0T3BlbklEIiwidXNlcm5hbWUiOiJ0ZXN0Tmlja25hbWUiLCJleHAiOjE3NTc5MDY0MzYsImlzcyI6ImJsdWViZWxsIn0.TZBVGPcb-2N8ORH7BWp_NQ4-UFdgVMVXoHlUi_mcBLs'
		}
		console.log(options)
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)


/**
 * 请求函数
 * @param Uniapp.RequestOptions
 * @returns Promise
 * 
 *  1.返回Promise对象
 *  2.请求成功
 *    2.1 提取核心数据 res.data
 *    2.2 添加类型,支持泛型
 *  3.请求失败
 *    3.1 网络错误 => 提示用户换网络
 *    3.2 401错请 =>  清理用户信息,跳转到登录页
 *    3.3 其它错误 => 根据后端错误信息轻提示
 */
export interface ResponseData<T> {
	code: number
	msg: string
	data: T
}

enum Code {
	CodeSuccess = 1000,
	CodeInvalidParam,
	CodeUserExist,
	CodeUserNotExist,
	CodeInvalidPassword,
	CodeServerBusy,
	CodeNeedAuth,
	CodeInvalidToken
}

function ErrorDealWith<T>(code: Code, res: any) {
	switch (code) {
		case Code.CodeInvalidParam:
			showErrorTips(res)
			break;
		case Code.CodeUserExist:
			showErrorTips(res)
			break;
		case Code.CodeUserNotExist:
			showErrorTips(res)
			break;
		case Code.CodeInvalidPassword:
			showErrorTips(res)
			break;
		case Code.CodeServerBusy:
			showErrorTips(res)
			break;
		case Code.CodeNeedAuth:
			reLogin();
			break;
		case Code.CodeInvalidToken:
			reLogin();
			break;
	}
}

function reLogin() {
	const memeberStore = useMemberStore()
	memeberStore.clearProfile()
	uni.navigateTo({
		url: '/pages/login/login'
	})
}

function showErrorTips<T>(res: any) {
	uni.showToast({
		icon: "none",
		title: (res as ResponseData<T>).msg || '请示错误'
	})
}

export const http = <T>(options: UniApp.RequestOptions) => {
	return new Promise<ResponseData<T>>((resolve, reject) => {
		uni.request({
			...options,
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					const data = res.data as ResponseData<T>;
					if (data.code != Code.CodeSuccess) {
						ErrorDealWith(data.code, data);
						reject()
					} else {
						resolve(res.data as ResponseData<T>)
					}

				} else if (res.statusCode === 401) {//token失效
					const memeberStore = useMemberStore()
					memeberStore.clearProfile()
					uni.navigateTo({
						url: '/pages/login/login'
					})
					reject(res)
				} else {
					uni.showToast({
						icon: "none",
						title: (res.data as ResponseData<T>).msg || '请示错误'
					})
					reject(res)
				}

			},
			fail(err) {
				//网络错误 
				uni.showToast({
					icon: 'none',
					title: '网络错误,换个网络试试'
				})
				reject(err)
			}
		})
	})
}

